package com.cloud.web;
import com.alibaba.fastjson.JSON;
import com.cloud.common.BaseReturn;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;


@Component
public class LoginIntercept implements HandlerInterceptor {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        String authorization = request.getHeader("authorization");

        Class handlerClass = ClassUtils.getUserClass(handler);
        System.out.printf("aclass:"+handlerClass.getName());
        System.out.printf("aclass:"+handlerClass.getTypeName());
        boolean resAuthToken = this.verificationAuthToken(authorization);
        if (!resAuthToken) {
            Object returnMsg = JSON.toJSON(BaseReturn.build("403", "登录失效,请重新登录"));
            response.getWriter().print(returnMsg);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    private boolean verificationAuthToken(String authToken) {
        if (StringUtils.isBlank(authToken)) {
            //请登录
            return false;
        }
        String token = stringRedisTemplate.opsForValue().get(authToken);
        if (StringUtils.isBlank(token)) {
            return false;
        }
        //重置缓存时间
        stringRedisTemplate.opsForValue().set(authToken, token, 60 * 30, TimeUnit.SECONDS);
        return true;
    }
}
